using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Instedd.Labs.Geo.Library.Sms
{
    internal class CsvSenderNameLookupProvider : ISenderNameLookupProvider
    {
        Dictionary<string, string> numberToSenderName = new Dictionary<string, string>();
        private string path;

        public CsvSenderNameLookupProvider(string path)
        {
            Guard.ArgumentNotNullOrEmptyString(path, "path");

            this.path = path;

            Refresh();
        }

        public void Refresh()
        {
            Dictionary<string, string> numberToSenderName = new Dictionary<string, string>();

            using (StreamReader reader = File.OpenText(path))
            {
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    string[] fields = line.Split(",".ToCharArray());
                    numberToSenderName.Add(fields[0], fields[1]);
                }
            }

            this.numberToSenderName = numberToSenderName;
        }

        #region ISenderNameLookupProvider Members

        public string LookupSenderName(string number)
        {
            string senderName = null;

            if(!numberToSenderName.TryGetValue(number, out senderName))
            {
                // Default value
                senderName = number;
            }

            return senderName;
        }

        #endregion

        public Stream Stream
        {
            get { return File.Open(path, FileMode.OpenOrCreate); }
        }

        public void Reset()
        {
            using (Stream stream = File.Open(path, FileMode.Truncate)) { }
        }
    }
}
